<script setup lang="ts">
import type { NavbarProps, PullDownRefreshExpose } from 'sard-uniapp'
import type { CSSProperties } from 'vue'
import { useAppEnv } from '@/composables/app'

defineOptions({
  name: 'PageWrapper',
  options: {
    styleIsolation: 'shared',
  },
})

const props = withDefaults(defineProps<{
  navbar?: Partial<NavbarProps> | null
  capsule?: boolean
  search?: boolean
  tabbar?: boolean
  // 加载状态
  loading?: boolean
  // 禁用下拉刷新
  disablePullDownRefresh?: boolean
}>(), {
  navbar: () => ({}),
  loadMore: () => ({}),
  capsule: false,
  search: true,
  tabbar: false,
  loading: false,
  disablePullDownRefresh: false,
})

const emit = defineEmits<{
  refresh: []
}>()

const slots = defineSlots<{
  'navbar-left'?: () => void
  'navbar-right'?: () => void
  'capsule'?: () => void
  'title'?: () => void
  'search': () => void
}>()

const { VITE_APP_TITLE } = useAppEnv()

const defaultNavbarProps: Partial<NavbarProps> = {
  title: VITE_APP_TITLE,
  backText: '返回',
  showBack: true,
  fixed: true,
  statusBar: true,
}

const navbarProps = computed<Partial<NavbarProps>>(() => {
  return { ...defaultNavbarProps, ...props.navbar }
})

const style = computed<CSSProperties>(() => {
  return {
    height: `calc(100vh - ${props.tabbar ? 'var(--sar-tabbar-height)' : '0px'})`,
  }
})

const pullDownRefresh = ref<PullDownRefreshExpose>()

function onScroll(event: any) {
  pullDownRefresh.value?.enableToRefresh(event.detail.scrollTop === 0)
}
function onScrolltoupper() {
  pullDownRefresh.value?.enableToRefresh(true)
}

function onRefresh() {
  emit('refresh')
}
</script>

<template>
  <view class="page-wrapper" :style="style">
    <sar-navbar v-if="navbar !== null" v-bind="navbarProps">
      <template v-if="Boolean(slots['navbar-left'])" #left>
        <slot name="navbar-left" />
      </template>
      <template v-if="Boolean(slots['navbar-right'])" #right>
        <slot name="navbar-right" />
      </template>
      <template v-if="Boolean(slots.title)" #title>
        <slot name="title" />
      </template>
    </sar-navbar>

    <view class="fixed left-0 top-0 z-999">
      <sar-status-bar />
      <Capsule v-if="capsule" root-class="mt-24rpx ml-24rpx" />
    </view>

    <scroll-view scroll-y :throttle="false" class="flex-1 overflow-y-hidden" @scroll="onScroll" @scrolltoupper="onScrolltoupper">
      <sar-pull-down-refresh ref="pullDownRefresh" :loading="loading" :disabled="disablePullDownRefresh" @refresh="onRefresh">
        <slot />
      </sar-pull-down-refresh>
    </scroll-view>
  </view>
</template>

<style lang="scss" scoped>
.page-wrapper {
  display: flex;
  flex-direction: column;
}
</style>
